package org.dylan.evernote;

import java.util.List;

import org.dylan.keepnote.KNote;
import org.dylan.keepnote.KNoteExtractor;

import com.evernote.edam.error.EDAMNotFoundException;
import com.evernote.edam.error.EDAMSystemException;
import com.evernote.edam.error.EDAMUserException;
import com.evernote.edam.type.Tag;
import com.evernote.thrift.TException;

/**
 * 
 * 
 * @Copyright: Copyright (c) 2013 FFCS All Rights Reserved
 * @Company: 北京福富软件有限公司
 * @author 陈作朋 Oct 26, 2013
 * @version 1.00.00
 * @history:
 * 
 */
public class KeepnoteToTag {

	public static void createTag(EDAMContext context, String pguid, KNote knote) throws EDAMUserException, EDAMSystemException, EDAMNotFoundException, TException, InterruptedException {
		// System.out.println("ptag:" + pguid + ",knote:" + knote.getTitle());
		Tag tag = new Tag();
		String name = knote.getName();
		tag.setName(name);
		tag.setParentGuid(pguid);
		System.out.println("creating tag:" + tag);
		Tag createdTag;
		try {
			/*createdTag = context.getNoteStore().createTag(tag);
			String guid = createdTag.getGuid();*/
			String guid="aaa";
			List<KNote> childs = knote.getChilds();
			for (KNote cknote : childs) {
				createTag(context, guid, cknote);
			}
		} catch (EDAMSystemException e) {
			e.printStackTrace();
			int wait = e.getRateLimitDuration() + 5;
			System.out.println("wait:" + wait);
			Thread.sleep(wait * 1000);
			createTag(context, pguid, knote);
		} catch (Exception e) {
			System.err.println("--ERROR--tag:"+tag+",content:"+ knote.getContent());
			e.printStackTrace();
		}
	}

	public static void createTag(KNote note) throws Exception {
		try {
			EDAMContext context = new EDAMContext();
			createTag(context, null, note);
		} catch (Exception e) {
			e.printStackTrace();
			if (e.getCause() instanceof EDAMSystemException) {
				EDAMSystemException edame = (EDAMSystemException) e.getCause();
				int wait = edame.getRateLimitDuration() + 5;
				System.out.println("wait:" + wait);
				Thread.sleep(wait * 1000);
				createTag(note);
			}
		}

	}

	public static void main(String[] args) throws Exception {
		String path = "/home/dylan/Data/n/Java";
		KNote note = KNoteExtractor.extract(path);
		createTag(note);
		// System.out.println(note);
	}

}
